package com.ebt.m.utils;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.Base64;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 图片操作工具包
 *
 * @author Michael.li
 */
public class ImageUtils {
    /**
     * @param pathName
     * @return
     */
    public static Bitmap decodeFile2Bitmap(String pathName) {
        return BitmapFactory.decodeFile(pathName, getDefaultOptions());
    }

    public static Bitmap decodeFile2Bitmap(String pathName, BitmapFactory.Options options) {
        return BitmapFactory.decodeFile(pathName, options);
    }

    // public static Bitmap decodeFile2Bitmap(int usage, String path)
    // {
    // return decodeFile2Bitmap(formatImagePath(usage, path));
    // }

    /**
     *
     * @param usage
     * @param path
     * @param reqWidth
     *            需要的宽度
     * @param reqHeight
     *            需要的高度
     * @return
     */
    // public static Bitmap decodeFile2Bitmap(int usage, String path, int
    // reqWidth, int reqHeight)
    // {
    // final BitmapFactory.Options options = new BitmapFactory.Options();
    // options.inJustDecodeBounds = true;
    // String pathName = formatImagePath(usage, path);
    //
    // BitmapFactory.decodeFile(pathName, options);
    // // Calculate inSampleSize
    // options.inSampleSize = calculateInSampleSize(options, reqWidth,
    // reqHeight);
    //
    // // Decode bitmap with inSampleSize set
    // options.inJustDecodeBounds = false;
    //
    // options.inPurgeable = true;
    // options.inInputShareable = true;
    //
    // Bitmap bitmap = BitmapFactory.decodeFile(pathName, options);
    // return bitmap;
    // }

    /**
     * 计算图片缩放比例
     *
     * @param options
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            // Calculate ratios of height and width to requested height and
            // width
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);

            // Choose the smallest ratio as inSampleSize value, this will
            // guarantee a final image with both dimensions larger than or equal
            // to therequested height and width.
            inSampleSize = Math.min(heightRatio, widthRatio);
        }

        return inSampleSize;
    }

    public static Bitmap decodeFile2Bitmap(InputStream inputStream) {
        Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, getDefaultOptions());
        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    private static BitmapFactory.Options getDefaultOptions() {
        BitmapFactory.Options options = new BitmapFactory.Options();

        // options.inDensity = 2;//getDisplayMetrics().densityDpi;
        // options.inTargetDensity =2;//
        // getResources().getDisplayMetrics().densityDpi;

        options.inPurgeable = true;
        options.inInputShareable = true;
        options.inSampleSize = 1;// scale
        return options;
    }

    /**
     * 从assets文件夹中获得图片
     *
     * @param context
     * @param filepath
     * @return
     */
    public static Bitmap getBitmapFromAsset(Context context, String filepath) {
        AssetManager manager = context.getAssets();
        InputStream inputStream;
        try {
            inputStream = manager.open(filepath);
            return decodeFile2Bitmap(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @param context
     * @param id
     * @return
     */
    public static Bitmap getBitmapFromDrawable(Context context, int id) {
        return BitmapFactory.decodeResource(context.getResources(), id);
    }

    /**
     * 获取等比例的缩略图
     *
     * @param source
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    public static Bitmap extractThumbnail(Bitmap source, int reqWidth, int reqHeight) {
        if (source == null) {
            return null;
        }
        int width = source.getWidth();
        int height = source.getHeight();
        // 计算缩放比例
        float scale = Math.min((float) reqWidth / (float) width, (float) reqHeight / (float) height);
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scale, scale);
        // 得到新的图片
        Bitmap bitmap = Bitmap.createBitmap(source, 0, 0, width, height, matrix, true);
        return bitmap;
    }

    /**
     * 图片去色,返回灰度图片
     *
     * @param bmpOriginal 传入的图片
     * @return 去色后的图片
     */
    public static Bitmap toGrayscale(Bitmap bmpOriginal) {
        int width, height;
        height = bmpOriginal.getHeight();
        width = bmpOriginal.getWidth();

        Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        Canvas c = new Canvas(bmpGrayscale);
        Paint paint = new Paint();
        ColorMatrix cm = new ColorMatrix();
        cm.setSaturation(0);
        ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
        paint.setColorFilter(f);
        c.drawBitmap(bmpOriginal, 0, 0, paint);
        return bmpGrayscale;
    }

    /**
     * 去色同时加圆角
     *
     * @param bmpOriginal 原图
     * @param pixels      圆角弧度
     * @return 修改后的图片
     */
    public static Bitmap toGrayscale(Bitmap bmpOriginal, int pixels) {
        return toRoundCorner(toGrayscale(bmpOriginal), pixels);
    }

    /**
     * 把图片变成圆角
     *
     * @param bitmap 需要修改的图片
     * @param pixels 圆角的弧度
     * @return 圆角图片
     */
    public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {

        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = pixels;

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        return output;
    }

    /**
     * 从Base64字符串解码出图片
     *
     * @param imgByteStr
     * @return
     */
    public static Bitmap decodeBitmapFromBase64Str(String imgByteStr) {
        Bitmap bitmap = null;
        if (imgByteStr == null) {
            return null;
        }
        byte[] bytes = Base64.decode(imgByteStr, Base64.DEFAULT);
        bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        return bitmap;
    }

    /**
     * bitmap转为base64
     *
     * @param bitmap
     * @return
     */
    public static String encodeBitmapToPngBase64(Bitmap bitmap) {

        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
                baos.flush();
                baos.close();
                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static void copyAssetsToSD(Context context, String src, String target) {
        InputStream myInput;
        OutputStream myOutput;
        try {
            myOutput = new FileOutputStream(target);
            myInput = context.getAssets().open(src);
            byte[] buffer = new byte[1024];
            int length = myInput.read(buffer);
            while (length > 0) {
                myOutput.write(buffer, 0, length);
                length = myInput.read(buffer);
            }
            myOutput.flush();
            myInput.close();
            myOutput.close();
            buffer = null;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void saveBitmap(Bitmap src, String path, String picName) {
        File f = new File(path, picName);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            src.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static Bitmap getLoacalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * base64编码字符集转化成图片文件。
     *
     * @param base64Str--data:image/png;base64
     * @param path      文件存储路径
     * @return 是否成功
     */
    public static boolean base64ToFile(String base64Str, String path) {
        byte[] data = Base64.decode(base64Str.split(",")[1], Base64.DEFAULT);
        for (int i = 0; i < data.length; i++) {
            if (data[i] < 0) {
                //调整异常数据
                data[i] += 256;
            }
        }
        OutputStream os = null;
        try {
            os = new FileOutputStream(path);
            os.write(data);
            os.flush();
            os.close();
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

    }

}
